#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
足球赛事分析对口型视频生成脚本
根据JSON格式的对话生成音频、图片，最后使用WaveSpeedAI生成对口型视频
"""

import sys
import os
import json
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.processors.lip_sync_generator import LipSyncGenerator
from src.processors.wavespeed_ai import WaveSpeedAI


def generate_football_analysis_video():
    """生成足球赛事分析对口型视频"""
    print("=== 足球赛事分析对口型视频生成 ===")
    
    # 初始化处理器
    generator = LipSyncGenerator()
    wavespeed_ai = WaveSpeedAI()  # 会从环境变量WAVESPEED_API_KEY获取API密钥
    
    # 创建足球赛事分析对话（葡萄牙语-巴西）
    # 对话简短，控制在30秒内
    json_input = {
        "background_image": None,  # 不提供背景图片，触发图片生成
        "dialogue": [
            {
                "speaker": "left", 
                "text": "E aí galera! Hoje o grande jogo é Palmeiras contra Corinthians."
            },
            {
                "speaker": "right", 
                "text": "O Palmeiras tá mandando muito bem, principalmente em casa."
            },
            {
                "speaker": "left", 
                "text": "Mas o Corinthians tem uma defesa muito forte, pode complicar."
            },
            {
                "speaker": "right", 
                "text": "Meu palpite: 2 a 1 para o Palmeiras. O que vocês acham?"
            }
        ]
    }
    
    print("输入对话内容 (葡萄牙语-巴西):")
    for i, turn in enumerate(json_input["dialogue"]):
        print(f"  {i+1}. {turn['speaker']}: {turn['text']}")
    
    # 第一步：处理输入，生成音频和图片
    print("\n[步骤1/3] 正在生成音频和背景图片...")
    audio_image_result = generator.process_json_input(json_input)
    
    if not audio_image_result["success"]:
        print("✗ 音频和图片生成失败!")
        print(f"  错误信息: {audio_image_result.get('error', '未知错误')}")
        return
    
    print("✓ 音频和图片生成成功!")
    print(f"  输出文件夹: {audio_image_result['folder_path']}")
    
    # 第二步：使用WaveSpeedAI上传文件并生成视频
    print("\n[步骤2/3] 正在使用WaveSpeedAI生成对口型视频...")
    folder_path = Path(audio_image_result['folder_path'])
    
    # 检查是单人还是两人对话
    if "audio_file" in audio_image_result:
        # 单人说话场景
        audio_file = audio_image_result["audio_file"]
        print("检测到单人说话场景")
        
        # 上传文件并生成视频
        video_url = wavespeed_ai.generate_single_video(
            audio_path=audio_file,
            image_path=str(folder_path / "background.png"),
            resolution="480p"
        )
    else:
        # 两人对话场景
        left_audio_file = audio_image_result["left_audio_file"]
        right_audio_file = audio_image_result["right_audio_file"]
        print("检测到两人对话场景")
        
        # 上传文件并生成视频
        video_url = wavespeed_ai.generate_conversation_video(
            left_audio_path=left_audio_file,
            right_audio_path=right_audio_file,
            image_path=str(folder_path / "background.png"),
            order="meanwhile",
            resolution="480p"
        )
    
    # 第三步：输出结果
    print("\n[步骤3/3] 处理完成")
    if video_url:
        print("✓ 对口型视频生成成功!")
        print(f"  视频URL: {video_url}")
        print("\n请访问以上URL下载生成的对口型视频。")
    else:
        print("✗ 对口型视频生成失败!")
        print("  请检查API密钥和网络连接，或稍后重试。")


def main():
    """主函数"""
    print("开始生成足球赛事分析对口型视频")
    print("=" * 60)
    
    # 检查API密钥
    elevenlabs_api_key = os.getenv("ELEVENLABS_API_KEY")
    wavespeed_api_key = os.getenv("WAVESPEED_API_KEY")
    
    if not elevenlabs_api_key:
        print("警告: 未设置 ELEVENLABS_API_KEY 环境变量")
        print("请设置该环境变量以生成音频")
        return
    
    if not wavespeed_api_key:
        print("警告: 未设置 WAVESPEED_API_KEY 环境变量")
        print("请设置该环境变量以生成视频")
        return
    
    try:
        generate_football_analysis_video()
    except Exception as e:
        print(f"生成过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
    
    print("\n" + "=" * 60)
    print("视频生成流程完成")


if __name__ == "__main__":
    main()